﻿using AutoRegistDependency.Attributes;
using Microsoft.Extensions.Logging;
using Models.Entities;
using PacketDotNet.Utils;
using PacketDotNet;
using Repositories.Base;
using Services.Base;
using SharpPcap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpPcap.LibPcap;
using System.Net.NetworkInformation;
using Core.Extension;

namespace Services.Equ
{
    [Component]
    public class EquService : BaseService<EquInfo>, IEquService
    {
        public EquService(IBaseRepository<EquInfo> repository, ILogger<EquInfo> logger) : base(repository, logger)
        {
        }

        public List<ILiveDevice> GetDevices()
        {
            return CaptureDeviceList.Instance.Where(t=>t.GetDeviceMacAddr()!= null).ToList();
        }

        public Task<List<EquInfo>> SearchEquInfo(ILiveDevice device)
        {
            return Task.Run(() =>
            {
                List<byte[]> list = new List<byte[]>();
                var Equ = new List<EquInfo>();
                device.Open();
                device.Filter = ConstParameters.SearchFliter;
                var header = ConstParameters.GetSearchHeader(device.GetDeviceMacAddr()!);
                var ethernetPacket = new EthernetPacket(new ByteArraySegment(header));
                ethernetPacket.PayloadData = ConstParameters.SearchPayload;
                device.OnPacketArrival += (sender, args) =>
                {
                    var p = args.GetPacket();
                    list.Add(p.Data);
                    if (p.Data[16]==0x05 && p.Data[17] == 0x01)
                    {
                        var bodyData = p.Data[26..^1];
                        EquInfo equInfo = new EquInfo();
                        equInfo.Init(bodyData);
                        Equ.Add(equInfo);
                    }
                };
                device.StartCapture();
                device.SendPacket(ethernetPacket);
                var lastTime = DateTime.Now.AddSeconds(ConstParameters.TimeOut);
                Thread.Sleep(ConstParameters.TimeOut * 1000);
                device.Close();
                return Equ;
            });
        }
        public override async Task<bool> AddAsync(List<EquInfo> entities)
        {
            await repository.DeleteAsync(t => true);
            await repository.AddAsync(entities);
            return true;
        }
        //private List<EquInfo> ConvertMessage(List<byte[]> byteList)
        //{
        //    List<EquInfo> equInfos = new List<EquInfo>();
        //    foreach (var item in byteList)
        //    {
        //        if (item[2]==0x05 && item[3] == 0x01)
        //        {
        //            string msg=Convert.tostri
        //        }
        //    }
        //}

    }
}
